#include "data.h"
#include "util.h"
#include <regex>

namespace NS_TIEC {
  ByteArray ByteArray::kEmpty = {nullptr, 0};

  Uri Uri::fromString(const String& uri_string) {
    Uri uri;
    const std::regex pattern(
        "(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"
    );
    std::match_results<std::string::const_iterator> matches;
    std::regex_match(uri_string, matches, pattern);
    const size_t n = matches.size();
    for (size_t i = 1; i < n; ++i) {
      if (!matches[i].str().empty()) {
        switch(i) {
          case 2: uri.scheme_ = matches[i].str(); break;
          case 4: uri.authority_ = matches[i].str(); break;
          case 5: uri.path_ = matches[i].str(); break;
          case 7: uri.query_ = matches[i].str(); break;
          case 9: uri.fragment_ = matches[i].str(); break;
          default: break;
        }
      }
    }
    return uri;
  }

  String Uri::getScheme() {
    return scheme_;
  }

  String Uri::getAuthority() {
    return authority_;
  }

  String Uri::getPath() {
    return path_;
  }

  String Uri::getQuery() {
    return query_;
  }

  String Uri::getFragment() {
    return fragment_;
  }

  String Uri::asString() {
    String res;
    if (!scheme_.empty()) {
      res += scheme_ + "://";
    }
    if (!authority_.empty()) {
      res += authority_;
    }
    if (!path_.empty()) {
      res += path_;
    }
    if (!query_.empty()) {
      res += "?" + query_;
    }
    if (!fragment_.empty()) {
      res += "#" + fragment_;
    }
    return res;
  }

  WString Uri::asWString() {
    return toWString(asString());
  }
}